/**
 * 
 */
package language;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Main Class of this Framework
 * @author Kevin Wagner
 * @version 1.0
 */
public class LanguageProfiler {

	private ArrayList<String> languages=new ArrayList<String>();
	private NodeList nlist;
	private String lang=Locale.getDefault().getLanguage();

	/**
	 * 
	 */
	public LanguageProfiler() {
		File file = new File("language.xml");
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(file);
			NodeList nList = doc.getElementsByTagName("supported");
			
			if(nList.getLength()>1){
				throw new Exception("<supported> darf nur einmal in der xml Datei auftauchen");
			}
			Node node=nList.item(0);
			if(node.getNodeType()==Node.ELEMENT_NODE){
				Element el=(Element)node;
				nList=el.getElementsByTagName("lang");
				for(int i=0;i<nList.getLength();i++){
					languages.add(nList.item(i).getTextContent());
				}
			}
			this.nlist = doc.getElementsByTagName("entry");
		} catch (Exception e) {
		}
	}
	
	/**
	 * @param key
	 * @return the localized String for the given key
	 */
	public String getLocalizedString(String key){
		if(nlist==null){
			return "No Value found";
		}
		for(int i=0;i<nlist.getLength();i++){
			Node node=nlist.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				Element eElement = (Element) node;
				if(eElement.getElementsByTagName("key").item(0).getTextContent().equals(key)){
					return eElement.getElementsByTagName(lang).item(0).getTextContent();
				}
			}
		}
		return "No Value found";
	}
	
	/**
	 * @return list of supported languages
	 */
	public ArrayList<String> getSupportedLanguages(){
		return languages;
	}
	
	/**
	 * @param l the new Locale
	 */
	public void setLang(Locale l){
		lang=l.getLanguage();
	}

}
